package com.longrise.android.loaddata.newloaddata;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Objects.ResultSetMetaData;
import com.longrise.android.loaddata.ObserverCallBack;
import com.longrise.android.util.IntenetUtil;

import org.apache.http.HttpResponse;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * Created by chengsan on 16/5/20.
 */
public class LoadDataManager2 extends LoadDataManagerFather
{
    private static LoadDataManager2 loadDataManager2 = null;


    public static LoadDataManager2 getInstance(Context context)
    {
        if(null == loadDataManager2)
        {
            synchronized (LoadDataManager2.class)
            {
                loadDataManager2 = new LoadDataManager2(context);
            }
        }
        return loadDataManager2;
    }

    public LoadDataManager2(Context context)
    {
        super(context);
        this.context = context;
    }


    /**
     * 请求服务2
     * @param key
     *        用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl
     *        服务的URL
     * @param serviceName
     *        服务名
     * @param bean
     *        参数
     * @param openCache
     *        是否开缓存
     * @param onRequestCompleteListener
     *        请求完成回调接口
     */
    public void callService2(final String key, final String serviceUrl, final String serviceName,
                            final EntityBean bean, boolean openCache,final OnRequestCompleteListener onRequestCompleteListener)
    {
        if(null != context)
        {
            if(IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_NONE)
            {
                if(null != onRequestCompleteListener)
                {
                    onRequestCompleteListener.onError(key,serviceName,ResultType.NoNetWorks);
                    onRequestCompleteListener.onFinished(key,serviceName);
                }
                if(this.showNetNotice)
                {
                    Toast.makeText(context,"没有网络连接",Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }

        Map<String, String> map = null;
        if(bean != null)
        {
            ResultSetMetaData[] keys = bean.toResultSet().getMetaData();
            if(null != keys)
            {
                map = new HashMap<String, String>();
                for (int i = 0; i < keys.length; i++)
                {
                    String beanKey = keys[i].getName();
                    String value = null;
                    Object object = bean.get(beanKey);
                    //将所有的类型全部转换成String类型
                    if (object != null)
                    {
                        if ((object instanceof String))
                        {
                            value = object.toString();
                        }
                        else if ((object instanceof Integer))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Long))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Number))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Boolean))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof BigDecimal))
                        {
                            value = String.valueOf(object);
                        }
                        else
                        {
                            value = JSONSerializer.getInstance().Serialize(object);
                        }
                    }

                    map.put(beanKey, value);
                }
            }
        }

        //初始化线程对象
        HttpRunnable httpRunnable = new HttpRunnable();
        httpRunnable.setAppVersion(this.appVersion);
        httpRunnable.setMap(map);
        httpRunnable.setRequestType(requestType);
        httpRunnable.setUrl(serviceUrl+"/"+serviceName+"/query");
        httpRunnable.setCookID(this.cookID);
        httpRunnable.setLoadCache(openCache);
        httpRunnable.setCacheDic(this.cacheDic);
        httpRunnable.setContext(this.context);
        httpRunnable.setMobileTimeOut(this.mobileTimeOut);
        httpRunnable.setWifiTimeOut(wifiTimeOut);

        //设置最新的CookID值
        httpRunnable.setOnCookIDListener(new OnCookIDListener()
        {
            @Override
            public void onCookID(String cookIDStr)
            {
                cookID = cookIDStr;
            }
        });
        httpRunnable.setCallBack(new ObserverCallBack()
        {
            @Override
            public void back(String data, String url, HttpResponse httpResponse)
            {
                if(null == data || "".equals(data))
                {
                    if(count > 3)
                    {
                        count = 0;
                    }
                    else
                    {
                        //判断是否session过期
                        if(loginInfoBean != null && httpResponse != null)
                        {
                            count++;
                            if(httpResponse.getStatusLine().getStatusCode() == 200)
                            {
                                getCookIdService(key, serviceUrl, serviceName, bean, onRequestCompleteListener);
                                return;
                            }
                        }
                    }
                    if(onRequestCompleteListener != null)
                    {
                        onRequestCompleteListener.onError(null,serviceName,ResultType.Failure);
                    }
                }
                else
                {
                    count = 0;
                    //序列化成Bean对象
                    EntityBean bean = (EntityBean) JSONSerializer.getInstance().DeSerialize(data, EntityBean.class);
                    if(null != onRequestCompleteListener)
                    {
                        onRequestCompleteListener.onSuccess(null, serviceName, bean);
                    }
                }

                if(null != onRequestCompleteListener)
                {
                    onRequestCompleteListener.onFinished(key,serviceName);
                }
            }
        });

        //加入数组中
        if(httpRunnableHashMap != null)
        {
            httpRunnableHashMap.put(key,httpRunnable);
        }
        //加入线程池中
        ThreadPool.execute(httpRunnable);
    }

    /**
     * 请求服务
     * @param key
     *        用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl
     *        服务的URL
     * @param serviceName
     *        服务名
     * @param bean
     *        参数
     * @param onRequestCompleteListener
     *        请求完成回调接口
     */
    public void callService(String key,String serviceUrl,String serviceName,
                            EntityBean bean,OnRequestCompleteListener onRequestCompleteListener)
    {
        callService2(key,serviceUrl,serviceName,bean,false,onRequestCompleteListener);
    }


    /**
     * 重新登录
     * @param key
     * @param serviceUrl
     * @param serviceName
     * @param bean
     * @param onRequestCompleteListener
     */
    private void getCookIdService(final String key,final String serviceUrl,final String serviceName,
                                  final EntityBean bean,final OnRequestCompleteListener onRequestCompleteListener)
    {
        Map<String, String> map = null;
        if(bean != null)
        {
            ResultSetMetaData[] keys = null;
            EntityBean tempBean = this.loginInfoBean.getBean(PARAMBEAN_KEY_NAME);
            if(null != tempBean)
            {
                keys = tempBean.toResultSet().getMetaData();
            }
            if(null != keys)
            {
                map = new HashMap<String, String>();
                for (int i = 0; i < keys.length; i++)
                {
                    String beanKey = keys[i].getName();
                    String value = null;
                    Object object = tempBean.get(beanKey);
                    //将所有的类型全部转换成String类型
                    if (object != null)
                    {
                        if ((object instanceof String))
                        {
                            value = object.toString();
                        }
                        else if ((object instanceof Integer))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Long))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Number))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof Boolean))
                        {
                            value = String.valueOf(object);
                        }
                        else if ((object instanceof BigDecimal))
                        {
                            value = String.valueOf(object);
                        }
                        else
                        {
                            value = JSONSerializer.getInstance().Serialize(object);
                        }
                    }

                    map.put(beanKey, value);
                }
            }
        }


        //初始化线程对象
        HttpRunnable httpRunnable = new HttpRunnable();
        httpRunnable.setAppVersion(this.appVersion);
        httpRunnable.setMap(map);
        httpRunnable.setRequestType(requestType);
        httpRunnable.setUrl(serviceUrl);
        httpRunnable.setCookID(this.cookID);
        //设置最新的CookID值
        httpRunnable.setOnCookIDListener(new OnCookIDListener()
        {
            @Override
            public void onCookID(String cookIDStr)
            {
                cookID = cookIDStr;
            }
        });
        httpRunnable.setCallBack(new ObserverCallBack()
        {
            @Override
            public void back(String data, String url, HttpResponse httpResponse)
            {
                //发送广播
                Intent intent = new Intent("com.longrise.loginForCookId");
                intent.putExtra("data", data);
                if(null != context)
                {
                    context.sendBroadcast(intent);
                }

                if(null == data || "".equals(data))
                {
                    //回调接口
                    if(null != onRequestCompleteListener)
                    {
                        onRequestCompleteListener.onError(key,serviceName,ResultType.Failure);
                        onRequestCompleteListener.onFinished(key,serviceName);
                    }
                }
                else
                {
                    //重新请求当前服务
                    callService(key, serviceUrl, serviceName, bean, onRequestCompleteListener);
                }
            }
        });

        //加入数组中
        if(httpRunnableHashMap != null)
        {
            httpRunnableHashMap.put(key,httpRunnable);
        }
        //加入线程池中
        ThreadPool.execute(httpRunnable);
    }


    /**
     * 取消某个请求
     * @param key
     */
    public void cancelRequest(String key)
    {
        if(null == key || key.isEmpty())
        {
            return;
        }
        if(httpRunnableHashMap != null)
        {
            Iterator iterator = httpRunnableHashMap.entrySet().iterator();
            while (iterator.hasNext())
            {
                Map.Entry entry = (Map.Entry) iterator.next();
                String tempKey = (String) entry.getKey();
                if(key.equals(tempKey))
                {
                    HttpRunnable httpRunnable = httpRunnableHashMap.get(tempKey);
                    ThreadPool.remove(httpRunnable);
                    break;
                }
            }
        }
    }

    /**
     * 获取Key
     * @return
     */
    public String getKey()
    {
        return UUID.randomUUID().toString();
    }
}
